package com.itbaizhan.hint;

import org.apache.shardingsphere.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.hint.HintShardingValue;

import java.util.ArrayList;
import java.util.Collection;

/*强制路由 hint
*分片条件并不存在sql，而存在于外部业务逻辑。因此需要一种通过外部业务代码中指定路由配置的一种方式
* ，在ShardingSphere中叫做hint,如果使用hint强制路由，那么sql将无视原有的分片逻辑，
* 直接将路由到指定的数据节点上操作 */
public class MyHintShardingAlgorithm implements HintShardingAlgorithm<Long> {
    /*collection : 数据源*/


    @Override
    public Collection<String> doSharding(Collection<String> collection, HintShardingValue<Long> hintShardingValue) {

        ArrayList<String> result = new ArrayList<>();
        //collection是数据源
        for(String each: collection) {
            //hintShardingValue分片键
            for (Long value : hintShardingValue.getValues()) {
                if (each.endsWith(String.valueOf(value % 2)))
                    result.add(each);
            }
        }


        return result;
    }
}
